/**
 * @author Tobias Boehm
 *
 * 14.04.2011
 */
package org.anddev.andengine.extension.tbsengine.match.playerslot;

import org.anddev.andengine.extension.tbsengine.faction.AbsBaseFaction;
import org.anddev.andengine.extension.tbsengine.match.AbsServerMatchPreparation;
import org.anddev.andengine.extension.tbsengine.team.Team;

/**
 * This class represents the server-side implementation of {@link AbsPlayerSlot}.
 * <p>
 * Each BaseServerPlayerSlot belongs to an instance of an implementation of
 * {@link AbsServerMatchPreparation} which will provided by calling the constructor.
 * 
 * @author Tobias Boehm
 *
 * @param <FactionBaseClass> - Your implementation of {@link AbsBaseFaction}
 * @param <MatchPreprataionClass> - Your implementation of {@link AbsServerMatchPreparation}
 */
public class BaseServerPlayerSlot<FactionBaseClass extends AbsBaseFaction,
										  MatchPreprataionClass extends AbsServerMatchPreparation>
										  extends AbsPlayerSlot<FactionBaseClass> implements Comparable<BaseServerPlayerSlot<FactionBaseClass,MatchPreprataionClass>>{
	

	protected static long slotsCreated;
		
	protected static long getNextSlotID(){
		
		if(slotsCreated == Long.MAX_VALUE){
			
			slotsCreated = Long.MIN_VALUE;
		
		}else{
			
			slotsCreated++;
		}
			
		return slotsCreated;
	}
	
	protected final MatchPreprataionClass mMatch;
	
	
	public BaseServerPlayerSlot(final MatchPreprataionClass pMatch, final Team pTeam, final FactionBaseClass pFaction){
		
		super(getNextSlotID(), pTeam, pFaction, SlotState.OPEN);
		
		this.mMatch = pMatch;
	}
		
	public void removePlayer(){
		
		this.mPlayer = null;
	}
		
	@Override
	public void setTeam(Team pNewTeam) {
		
		if(this.hasPlayer()){
			
			this.mTeam.remove(this.mPlayer);
			
			pNewTeam.add(this.mPlayer);
					
		} 
		
		super.setTeam(pNewTeam);
	}
	
	public void setSlotState(final SlotState pNewPlayerSlotState) {
		
		this.mPlayerSlotState = pNewPlayerSlotState;
		
		if((pNewPlayerSlotState == SlotState.OPEN) || (pNewPlayerSlotState == SlotState.CLOSED)){
					
			this.mPlayer = null;
		}
	}
	
	
	@Override
	public int compareTo(final BaseServerPlayerSlot<FactionBaseClass, MatchPreprataionClass> another) {
		
		final Long idThis = this.getSlotID();
		
		final Long idANother = another.getSlotID();
		
		return (idThis.compareTo(idANother));
	}
	
	@Override
	public boolean equals(Object o) {
		
		if(o instanceof BaseServerPlayerSlot){
			
			return (this.mSlotID == ((BaseServerPlayerSlot)o).getSlotID());
		}
		
		return super.equals(o);
	}
}
